const Base = require('./base.js');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.region = this.model('store/region');
	}
	async indexAction() {
		let pid = this.get("pid");
		let regions = await this.region.getChilds(pid);

		if(this.isPost) {
			return this.success(regions);
		}
		this.assign("regions", regions);
		return this.display();
	}
	
	async selectAction() {
		
		let posts = this.post();
		const data = await this.region.getChilds(posts.pid);
		return this.json(data);
	}
	
	async childAction() {

		let pid = this.post("pid");
		let childs = await this.region.getChilds(pid);
		this.assign("regions", childs);
		return this.display();

	}

	
	async addAction() {
		if(this.isGet) {
			let pid = this.get("pid");

			if(pid) {
				let region = await this.region.findOne(pid);
				this.assign("parentRegion", region);

			}
			return this.display();

		}

		let posts = this.post();

		let region_id = await this.region.add({
			name: posts.name,
			pid: posts.parentId,
			type: posts.type
		});

		if(region_id == 0) {
			return this.fail("添加失败");
		}
		return this.success("添加成功");

	}

	async editAction() {
		if(this.isGet) {
			let id = this.get("id");

			if(id) {
				let region = await this.region.findOne(id);

				if(region.pid) {
					let parentRegion = await this.region.findOne(region.pid);

					this.assign("parentRegion", parentRegion);

				}

				this.assign("region", region);
				return this.display();
			}

		}

		let posts = this.post();

		let rows = await this.region.setOne(posts.id, {
			name: posts.name,
			pid: posts.parentId,
			type: posts.type
		});

		if(rows == 0) {
			return this.fail("修改失败");
		}
		return this.success("修改成功");
	}

	async treeAction() {

		let pid = this.get("pid");
		let regions = await this.region.getChilds(pid);
		var str = [];
		if(!think.isEmpty(regions)) {

			regions.forEach((o) => {
				let obj = {};
				obj.id = o.id;
				obj.text = o.name;
				obj.type = o.type;
				obj.children = o.type < 3 ? true : false;
				str.push(obj);
			});
		}

		return this.json(str);
	}

	

};